/*
 * Copyright (c) chb my copyright message. 2022-2023. All rights reserved.
 *
 */
// 导入这个是为了Vue.use(Vuex) 挂载vuex对象用来访问
import Vue from 'vue'
// 导入vuex包
import Vuex from 'vuex'

//挂载Vuex
Vue.use(Vuex)


//创建一个新的store实例
export default new Vuex.Store({
  state: {
    //   存放的键值对就是要管理的状态
    //如果本地浏览器有登录信息就直接获取
    user: {
      // 默认是空
      account: "",
    },
    playMusics: {
      id: '',
      images: '',
      title: '水星记',
      author: '薛之谦',
      musicUrl: '',
      state: 'false',
      length: 0,
      currentTime: 0,
      totalDivide: 0,//总分数
      totalSecond: 0,//总秒数
    },
    musicAudio: {
      music: new Audio(),//定义全局音乐audio
    }
  },
  actions: {
    changePlayMusics(item, playMusics) {
      item.commit('changePlayMusics', playMusics)
    },
    changeMusicUrl(item, url) {
      item.commit('changeMusicUrl', url)
    },
    changeMusicState(item, state) {
      item.commit("changeMusicState", state)
    },
    changeAudio(item, url) {
      item.commit('changeAudio', url)
    },
    changeCurrentTime(item, time) {
      item.commit('changeCurrentTime', time)
    },
    changeTotalTime(item, time) {
      item.commit('changeTotalTime', time)
    },

  },
//   方法，一般包含功能性方法和状态变量的set()get()方法
  mutations: {
    //成功登录才会进来这里
    loginSuccess(state, account) {
      //先把登录信息放进store.state的状态变量中方便后面调用
      state.user.account = account
      //把登录信息放进localStorage，让vue放进浏览器cookie中
      window.localStorage.setItem("account", account)
    },
    //修改状态变量只能通过这种方式
    //用来改变account的值的方法
    //外界只能通过该方法更改account的值
    setAccount(state, account) {
      this.user.account = account
    },
    changePlayMusics(state, playMusics) {
      // state.playMusics = playMusics
      state.playMusics.images = playMusics.images
      state.playMusics.title = playMusics.title
      state.playMusics.author = playMusics.article
    },
    changeMusicState(state, states) {
      state.playMusics.state = states
    },
    //向音乐传递值
    changeAudio(state, url) {
      state.musicAudio.music = new Audio(url)
      let music = state.musicAudio.music
      music.addEventListener('loadedmetadata', () => {
        state.playMusics.length = Math.floor(music.duration)
        state.playMusics.currentTime = Math.floor(music.currentTime)
      })
    },
    changeTotalTime(state, url) {
      state.playMusics.totalDivide = Math.floor(url / 60) < 10 ? '0' + Math.floor(url / 60) : Math.floor(url / 60)
      state.playMusics.totalSecond = Math.floor(url % 60 % 60) < 10 ? '0' + Math.floor(url % 60 % 60) : Math.floor(url % 60 % 60)
    },
    changeCurrentTime(state, url) {
      let music = state.musicAudio.music
      music.addEventListener('loadedmetadata', () => {
        state.playMusics.currentTime = Math.floor(music.currentTime)
      })
    }

  }
})
